<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="css/bootstrap.min.css"/>
    <link rel="stylesheet" href="css/font-awesome.css"/>
    <link rel="stylesheet" href="css/Lobibox.min.css">
    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/jquery.cookie.min.js"></script>
    <script src="js/vue.js"></script>
    <script src="js/Lobibox.js"></script>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    body {
        background-color: #EEEEEE;
    }

    .navbar-text a {
        color: #ffffff;
    }

    .login-text {
        margin-right: 50px;
    }

    .logo {
        color: #E94F4C;
        font-size: 35px;
        display: inline-block;
    }

    .search-box {
        height: 48px;
    }

    .input-group-addon {
        background-color: #E94F4C;
        border: none;
        color: #ffffff;
    }

    .control-icon {
        position: absolute;
        top: 50%;
    }

    .mgt38 {
        margin-top: 30px;
    }

    .thumbnail a img {
        height: 200px;
        width: 200px;
    }

    .thumbnail .description {
        height: 40px;
        overflow: hidden;
    }

    a:hover {
        text-decoration: none;
    }

    h3, p {
        text-align: center;
    }

    table tr {
        background-color: #ffffff;
    }


    .navbar-text a {
        color: #ffffff;
    }

    .login-text {
        margin-right: 50px;
    }


</style>
<body>
<nav class="navbar navbar-default navbar-inverse navbar-static-top">
    <div class="container-fluid">
        <div class="navbar-header">
            <a href="index.jsp" class="navbar-brand" style="color: #ffffff;"><i class="fa fa-sign-language"></i>
                寻欢易购</a>
        </div>
        <div id="loginPage">
            <p class="navbar-text navbar-right login-text">
                <a href="#2" id="loginName"></a><!--登录-->
            </p>
            <p class="navbar-text navbar-right">
                <a href="#2" id="register_exit" onclick="register_exit_btn()"></a><!--注册,退出-->
            </p>
        </div>
    </div>
</nav>
<div class="container-fluid">
    <div class="row">
        <div class="col-xs-8 col-xs-push-2">
            <table id="app" class="table">
                <thead>
                <tr>
                    <td>商品</td>
                    <td>单价</td>
                    <td>数量</td>
                    <td>小计</td>
                    <td>操作</td>
                </tr>
                </thead>
                <tbody v-for="g in goodList">
                <tr>
                    <td style="max-width: 200px;">
                        <div class="media">
                            <div class="media-left">
                                <a href="javascript: void(0);">
                                    <img class="media-object" height="80px" width="62px"
                                         :src="g.img">
                                </a>
                            </div>
                            <div class="media-body">
                                <h4 class="media-heading">{{g.title}}</h4>
                            </div>
                        </div>
                    </td>
                    <td>{{g.price}}</td>
                    <td>
                        <!---->
                        <div class="input-group" style="width: 150px;">
                            <!---->
                            <span v-if="g.num == 1" style="background-color: #e2e2e2;"
                                  class="input-group-addon">-</span>

                            <span v-if="g.num>1" onclick="reduceGoodNum(this)" :id="g.goodsID" class="input-group-addon"
                                  style="cursor: pointer;">-</span>

                            <input class="form-control" :value="g.num">
                            <!---->
                            <span class="input-group-addon" :id="g.goodsID" onclick="addGoodNum(this)"
                                  style="cursor: pointer;">+</span>
                        </div>
                    </td>
                    <td>{{g.amount}}</td>
                    <td>
                        <button :id="g.goodsID" onclick="deleteSpecifyGood(this)" class="btn btn-default">删除</button>
                    </td>
                </tr>
                </tbody>
                <tfoot>
                <tr v-if="goodList.length != 0">
                    <td colspan="5">
                        已选购 <span id="totalCount" style="color: red;">{{goodsSum}}</span> 件商品,
                        总价 <span style="color: red;" id="totalPrice">{{totalPrice}}</span>
                        <button onclick="gotoSettleCount()" class="btn btn-danger btn-lg">去结算</button>
                    </td>
                </tr>
                <!-- 如果没有商品，就是显示。
                -->
                <tr v-else>
                    <td colspan="5">暂无商品.<a href="index.jsp">去购物</a></td>
                </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>
</body>
<script>
<%--    <%@include file="syncCartAndNameDisplay.jsp"%>--%>

    // $.cookie("username",'ssx');
    // $.cookie('uId',28);


    var showLogin = $('#loginText');

    var vm = new Vue({
        el: '#app',
        data: {
            goodList: [],
            goodsSum: 0,
            totalPrice: 0
        }
    });

    //初始化页面
    window.onload = function () {
        //因为登陆功能尚未完成，因此渲染页面暂时不做登陆判断

        // if(!$.cookie('username')){
            getGoodListByStorage();
        // }
    };

    //购物车渲染页面，通过Storage取得数据，请求数据库取得相应商品信息
    function getGoodListByStorage() {
        var shoppingCart = localStorage.getItem('local_shopping_cart');
        if (shoppingCart != null) {
            $.ajax({
                url: '${pageContext.servletContext.contextPath}/good' ,
                type: 'post',
                // traditional:true,
                data: {
                    IDList: shoppingCart
                },
                dataType: 'json',
                success: function (_data) {
                    var shoppingCartObject = JSON.parse(shoppingCart);
                    var subjects = _data;
                    for (var i = 0; i < subjects.length; i++) {
                        // console.log(subjects[i])
                        var good = subjects[i];
                        var img = good.smallPic;
                        var goodsID = good.goodsId;
                        var title = good.title;
                        var price = good.price;
                        var num = shoppingCartObject[goodsID];
                        var amount = num * price;
                        vm.goodsSum += num;
                        vm.totalPrice = floatAdd(vm.totalPrice,amount);
                        vm.goodList.push({
                            img: 'http://localhost/' + img,
                            title: title,
                            price: price,
                            goodsID: goodsID,
                            num: num,
                            amount: amount
                        })
                    }
                }
            })
        }
    }


    //购物车增加商品
    function addGoodNum(btnTag) {
        //登陆状态下就同步到数据库
        if ($.cookie('username')) {
            var goodID = $(btnTag).prop('id');
            $.ajax({
                url: '${pageContext.servletContext.contextPath}/shoppingCart/add/'+goodID+'/'+$.cookie('uId'),
                type: 'PUT',
                dataType: 'json',
                success: function (_data) {
                    if (_data.code > 0) {
                        addGoodInStorage(btnTag);

                    } else {
                        showErrorBox(_data.msg)
                    }
                }
            });
        }
        //没有登陆的情况下，只更新Storage里面的数量
        else {
            addGoodInStorage(btnTag)
        }


    }

    //购物车减少商品数量（只能减到1）
    function reduceGoodNum(btnTag) {
        if ($.cookie('username')) {
            var goodID = $(btnTag).prop('id');
            $.ajax({
                url: '${pageContext.servletContext.contextPath}/shoppingCart/sub/'+goodID+'/'+$.cookie('uId'),
                type: 'PUT',
                dataType: 'json',
                success: function (_data) {
                    if (_data.code > 0) {
                        subGoodInStorage(btnTag);
                    } else {
                        showErrorBox(_data.msg)
                    }
                }
            });

        } else {
            subGoodInStorage(btnTag)
        }
    }

    //购物车删除对应的商品
    function deleteSpecifyGood(btnTag) {
        console.log("shopping - 297 - btnTag="+btnTag)
        if ($.cookie('username')) {
            var goodID = $(btnTag).prop('id');
            console.log("shopping - 299 -goodID="+goodID)
            $.ajax({
                url: '${pageContext.servletContext.contextPath}/shoppingCart/'+goodID+'/'+$.cookie('uId'),
                type: 'DELETE',
                dataType: 'json',
                success: function (_data) {
                    if (_data.code > 0) {
                        deleteGoodInStorage(btnTag);
                    } else {
                        showErrorBox(_data.msg)
                    }
                }
            });
        } else {
            deleteGoodInStorage(btnTag)
        }
    }

    function gotoSettleCount(btnTag) {
        window.location.href = "paymentPage.jsp";
    }


    //商品增加数目等添加到本地数据并渲染
    function addGoodInStorage(btnTag) {

        var shoppingCart = localStorage.getItem('local_shopping_cart');
        var goodID = $(btnTag).prop('id');
        var shoppingCartObject = JSON.parse(shoppingCart);

        var num = ++shoppingCartObject[goodID];
        for (var i = 0; i < vm.goodList.length; i++) {
            var good = vm.goodList[i];
            if (good.goodsID == goodID) {
                good.num = num;
                vm.goodsSum++;
                // good.amount += good.price;
                good.amount = floatAdd(good.amount,good.price);
                // vm.totalPrice += good.price;
                vm.totalPrice = floatAdd(vm.totalPrice,good.price);
            }
        }
        localStorage.setItem('local_shopping_cart', JSON.stringify(shoppingCartObject))
    }

    //商品减少数目等添加到本地数据并渲染
    function subGoodInStorage(btnTag) {
        var shoppingCart = localStorage.getItem('local_shopping_cart');
        var goodID = $(btnTag).prop('id');

        var shoppingCartObject = JSON.parse(shoppingCart);
        var num = --shoppingCartObject[goodID];

        for (var i = 0; i < vm.goodList.length; i++) {
            var good = vm.goodList[i];

            if (good.goodsID == goodID) {

                if (num == 0) {
                    num = 1;
                } else {
                    good.num = num;
                    vm.goodsSum--;
                   good.amount =  floatSub(good.amount,good.price);
                   vm.totalPrice =  floatSub(vm.totalPrice,good.price);
                }

            }
        }
        localStorage.setItem('local_shopping_cart', JSON.stringify(shoppingCartObject))

    }
    //商品删除数目等添加到本地数据并渲染
    function deleteGoodInStorage(btnTag) {
        var shoppingCart = localStorage.getItem('local_shopping_cart');

        var goodID = $(btnTag).prop('id');

        var shoppingCartObject = JSON.parse(shoppingCart);

        for (var i = 0; i < vm.goodList.length; i++) {
            var good = vm.goodList[i];
            if (good.goodsID == goodID) {
                delete shoppingCartObject[goodID];
                vm.goodList.splice(i, 1);
                vm.goodsSum = floatSub(vm.goodsSum,good.num);

                vm.totalPrice = floatSub(vm.totalPrice,(good.price*good.num));
            }
        }
        localStorage.setItem('local_shopping_cart', JSON.stringify(shoppingCartObject))

    }


    function showErrorBox(msgText) {

        Lobibox.notify('warning', {
            size: 'mini',
            delay: 2000,
            delayIndicator: false,
            title: false, //不给title
            msg: msgText,
            sound: false  // 不要音频

        })
    }

    /**
     * 解决两个数相加精度丢失问题
     * @param a
     * @param b
     * @returns {Number}
     */
    function floatAdd(a, b) {
        var c, d, e;
        if(undefined==a||null==a||""==a||isNaN(a)){a=0;}
        if(undefined==b||null==b||""==b||isNaN(b)){b=0;}
        try {
            c = a.toString().split(".")[1].length;
        } catch (f) {
            c = 0;
        }
        try {
            d = b.toString().split(".")[1].length;
        } catch (f) {
            d = 0;
        }
        e = Math.pow(10, Math.max(c, d));
        return  (floatMul(a, e) + floatMul(b, e)) / e;
    }

    /**
     * 解决两个数相减精度丢失问题
     * @param a
     * @param b
     * @returns {Number}
     */

    function floatSub(a, b) {
        var c, d, e;
        if(undefined==a||null==a||""==a||isNaN(a)){a=0;}
        if(undefined==b||null==b||""==b||isNaN(b)){b=0;}
        try {
            c = a.toString().split(".")[1].length;
        } catch (f) {
            c = 0;
        }
        try {
            d = b.toString().split(".")[1].length;
        } catch (f) {
            d = 0;
        }
        e = Math.pow(10, Math.max(c, d));
        return (floatMul(a, e) - floatMul(b, e)) / e;
    }


    function floatMul(a, b) {
        var c = 0,
            d = a.toString(),
            e = b.toString();
        try {
            c += d.split(".")[1].length;
        } catch (f) {}
        try {
            c += e.split(".")[1].length;
        } catch (f) {}
        return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
    }
    /**
     * 解决两个数相除精度丢失问题
     * @param a
     * @param b
     * @returns
     */
    function floatDiv(a, b) {
        var c, d, e = 0,
            f = 0;
        try {
            e = a.toString().split(".")[1].length;
        } catch (g) {}
        try {
            f = b.toString().split(".")[1].length;
        } catch (g) {}
        return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), floatMul(c / d, Math.pow(10, f - e));
    }
</script>
</html>